<template>
  <div class="search">
    <div class="header">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="userKey"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
      <div @click="onSearch">搜索</div>
    </div>
    <div class="historyList">
      <h2>历史记录</h2>
      <div
        class="historyItem"
        v-for="(value, index) in history"
        :key="index"
        @click="onSearch(index, value)"
      >
        {{ value }}
      </div>
    </div>
    <div class="resultList">
      <h2>搜索结果</h2>
      <router-link
        :to="'/articleDetail/' + item.id"
        v-for="item in searchList"
        :key="item.id"
        >{{ item.title }}</router-link
      >
    </div>
  </div>
</template>

<script>
import { search_article } from "@/apis/post.js";
import { Toast } from "vant";
export default {
  data() {
    return {
      userKey: "",
      history: [],
      searchList: [],
    };
  },
  mounted() {
    this.history =
      JSON.parse(localStorage.getItem("heimatoutiao_history")) || [];
  },
  methods: {
    async onSearch(i, keywords = this.userKey) {
      // vue事件中，如果没有传递参数，那么第一个参数会默认传递事件对象e，如果传递了就不会默认传递e
      // console.log(this.userKey);
      // console.log(a);
      // console.log("==", keywords);
      if (keywords == "") {
        Toast.fail("请先输入搜索内容");
        return;
      }
      // 搜索记录重复删除原来的添加新的;
      let index = this.history.indexOf(this.userKey);
      if (this.history.indexOf(this.userKey) != -1) {
        this.history.splice(index, 1);
      }
      this.history.unshift(this.userKey);
      localStorage.setItem(
        "heimatoutiao_history",
        JSON.stringify(this.history)
      );
      let res = await search_article(keywords);
      console.log("搜索结果", res);
      this.searchList = res.data.data;
    },
  },
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  height: 50px;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
  border-bottom: 1px solid #ccc;
  .van-search {
    flex: 1;
    padding: 5px 12px;
  }
}
.historyList,
.resultList {
  padding: 10px;
  border-bottom: 1px solid #ccc;
  .historyItem {
    line-height: 26px;
    border-bottom: 1px dashed #ccc;
  }
  h2 {
    line-height: 40px;
    font-weight: bold;
  }
  > a {
    display: block;
    text-decoration: underline;
    line-height: 30px;
    color: rgb(113, 112, 112);
  }
}
</style>